package an.qt5.javagather;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
//import android.hardware.usb.UsbManager;
//import android.hardware.usb.UsbDevice;
//import java.lang.String;

import java.util.HashMap;
import java.util.Iterator;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.hardware.usb.IUsbManager;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.IBinder;
import android.os.ServiceManager;
import android.text.TextUtils;

public class GatherBootUpReceiver extends BroadcastReceiver
{
    // 系统启动完成
    static final String ACTIONSYSSTART = "android.intent.action.BOOT_COMPLETED";
    static final String ACTIONDESTROY = "an.qt5.javagather.exception";
    static final String ACTIONRESTART = "an.qt5.javagather.restart";
//    static final String YOUR_APP_PACKAGE_NAMESPACE = "an.qt5.javagather";
//    static final String ACTION_USB_PERMISSION_APP =  "ACTION_USB_PERMISSION_ISSUER";
    @Override
    public void onReceive(Context context, Intent intent)
    {
        String action = intent.getAction();
        if(action == null)
        {
            return;
        }
        // 当收听到的事件是“BOOT_COMPLETED”时，就创建并启动相应的Activity和Service
        if (action.equals(ACTIONSYSSTART)) {
            //开机启动，不准调用PL2303HXDNative.OnNotify_LOG
            onStartActivity(context,100000);
        }
        else if(action.equals(ACTIONDESTROY)){
            PL2303HXDNative.OnNotify_LOG("异常退出启动");
            onReStartActivity(context,10000);
            //杀死当前进程
            android.os.Process.killProcess(android.os.Process.myPid());
        }
        else if(action.equals(ACTIONRESTART)){
            PL2303HXDNative.OnNotify_LOG("USB插入导致重启");
            onReStartActivity(context,10000);
            //杀死当前进程
            android.os.Process.killProcess(android.os.Process.myPid());
        }
//        else if(action.equals( ACTION_USB_PERMISSION_APP ))
//        {
//            try {
//                 UsbDeviceDescriptor deviceFilter = new UsbDeviceDescriptor();
//                 deviceFilter.packageName = intent.getStringExtra("packageName");
//                 deviceFilter.vendorId = intent.getIntExtra("vendorId", -1);
//                 deviceFilter.productId = intent.getIntExtra("productId", -1);
//                 deviceFilter.deviceClass = intent.getIntExtra("deviceClass", -1);
//                 deviceFilter.deviceSubclass = intent.getIntExtra("deviceSubclass", -1);

//                 PL2303HXDNative.OnNotify_LOG("vendorId="+deviceFilter.vendorId+",productId="+deviceFilter.productId
//                    +",deviceClass="+deviceFilter.deviceClass+",deviceSubclass="+ deviceFilter.deviceSubclass);
//                 if(TextUtils.isEmpty(deviceFilter.packageName)){
////                     logger.log("PackageName is Null");
//                     PL2303HXDNative.OnNotify_LOG("PackageName is Null");
//                     return;
//                 }

//                 PackageManager pm = context.getPackageManager();
//                 ApplicationInfo ai = pm.getApplicationInfo(deviceFilter.packageName, 0);

//                 UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
//                 IBinder b = ServiceManager.getService(Context.USB_SERVICE);
//                 IUsbManager service = IUsbManager.Stub.asInterface(b);
//                 HashMap<String, UsbDevice> deviceList = manager.getDeviceList();

////                 logger.log("List of usb devices was loaded. Number of attached devices: " +
////                         new Integer(deviceList.size()).toString());
//                 PL2303HXDNative.OnNotify_LOG("List of usb devices was loaded. Number of attached devices: " +
//                        new Integer(deviceList.size()).toString());
//                 if((deviceFilter.deviceClass != -1 && deviceFilter.deviceSubclass != -1) ||
//                         (deviceFilter.productId != -1 && deviceFilter.vendorId != -1))
//                 {

////                     logger.log("The usb permission will be granted for application " + ai.packageName);
//                     PL2303HXDNative.OnNotify_LOG("The usb permission will be granted for application " + ai.packageName);
//                     Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
//                     while (deviceIterator.hasNext()) {
//                         UsbDevice device = deviceIterator.next();
//                         if(device==null)
//                         {
//                             continue;
//                         }
//                         if(device.getVendorId() !=1659)
//                         {
//                             continue;
//                         }
//                         PL2303HXDNative.OnNotify_LOG("授权,device.getVendorId()="+device.getVendorId()
//                            +",device.getProductId()="+device.getProductId());
//                         if ((device.getDeviceClass() == deviceFilter.deviceClass &&
//                                 device.getDeviceSubclass() == deviceFilter.deviceSubclass) ||
//                                 (device.getVendorId() == deviceFilter.vendorId &&
//                                         device.getProductId() == deviceFilter.productId))
//                         {

//                             try {
//                                 PL2303HXDNative.OnNotify_LOG("Usb permission is granted (1) for application " +
//                                    ai.packageName + " for device " + device.toString() +
//                                    " and user " + ai.uid + " is granted");
//                                 PL2303HXDNative.OnNotify_LOG("service.grantDevicePermission(device, ai.uid)");
//                                 service.grantDevicePermission(device, ai.uid);
//                                 PL2303HXDNative.OnNotify_LOG("Usb permission is granted (2) for application " +
//                                    ai.packageName + " for device " + device.toString() +
//                                    " and user " + ai.uid + " is granted");
//                                 PL2303HXDNative.OnNotify_LOG("service.setDevicePackage(device, ai.packageName, ai.uid)");
//                                 service.setDevicePackage(device, ai.packageName, ai.uid);
////                                 logger.log("Usb permission is granted for application " +
////                                         ai.packageName + " for device " + device.toString() +
////                                         " and user " + ai.uid + " is granted");
//                             } catch (SecurityException se) {
////                                 logger.log(se.toString());
////                                 Log.e(TAG, se.toString());
//                                 PL2303HXDNative.OnNotify_LOG("授权异常"+se.toString());
//                             }
//                         }else{
//                            PL2303HXDNative.OnNotify_LOG("授权,device map deviceFilter error!");
//                         }

//                     }
//                 } else {
//                     PL2303HXDNative.OnNotify_LOG("Device params is Error "+deviceFilter.toString());
////                     logger.log("Device params is Error "+deviceFilter.toString());
//                 }
//             }
//             catch(Exception e)
//             {
////                 logger.log(e.toString());
////                 Log.e(TAG, e.toString());
//                 PL2303HXDNative.OnNotify_LOG("授权异常"+e.toString());
//             }
//        }
        else{
            ;
        }
    }

    public void onStartActivity(Context context,long Delayed)
    {
        // 开机启动Activity
        Intent boot = new Intent(context, PL2303HXDSerialPort.class);
        boot.putExtra("Delayed",Delayed);
        boot.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(boot);
    }
    public void onReStartActivity(Context context,long Delayed)
    {
        // 重启Activity
        Intent boot = new Intent(context, PL2303HXDSerialPort.class);
        boot.putExtra("PackageName",context.getPackageName());
        boot.putExtra("Delayed",Delayed);
        /*
        Intent.FLAG_ACTIVITY_CLEAR_TOP ： 销毁目标Activity和它之上的所有Activity，重新创建目标Activity。
        Intent.FLAG_ACTIVITY_CLEAR_TASK ： 启动Activity时，清除之前已经存在的Activity实例所在的task，这自然也就清除了之前存在的Activity实例！
        Intent.FLAG_ACTIVITY_NEW_TASK ： 很少单独使用，通常与FLAG_ACTIVITY_CLEAR_TASK或FLAG_ACTIVITY_CLEAR_TOP联合使用。
        */
        boot.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_CLEAR_TASK
            | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(boot);
    }
}
